#!/usr/bin/perl
# 
# Exercise 8.4
# 
# Write a subroutine that inserts an element into a sorted array. Hint: use the splice 
# Perl function to insert the element, as shown in Chapter 4.
#
# Answer to Exercise 8.4

use strict;
use warnings;

my @genes = qw(
xgene1 agene2 mgene3 zgene4 cgene5
);

my @sorted_genes = sort @genes;

print "Here are the existing genes: @sorted_genes\n\n";

print "Enter the new gene name: ";
my $new = <STDIN>;
chomp $new;

# We need to declare $i outside of the "for" loop so we can use the
# offset in the following "splice" function
my $i;

for($i=0; (@sorted_genes > $i) and (($new cmp $sorted_genes[$i]) != -1) ; ++$i) {
	;
}

splice(@sorted_genes, $i, 0, ($new));

print "Here are the existing genes: @sorted_genes\n\n";

exit;
